<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb style="margin-top: 10px; margin-bottom: 20px; margin-left: 25px;">
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>用户信息管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片区域-->
    <el-card>
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <!--搜索框-->
        <el-col :span="7" style="margin-bottom: 20px;">
          <el-input v-model="selectBy" placeholder="请输入用户名进行查询" clearable @clear="getUserList"
            :default-value="timeDefaultShow">
            <el-button slot="append" icon="el-icon-search" @click="selectById(selectBy)"></el-button>
          </el-input>
        </el-col>
        <!--添加用户按钮-->
        <el-col :span="4">
          <el-button type="primary" @click.native.prevent="addUserdialogVisible = true">添加用户</el-button>
        </el-col>
        <el-col :span="5" :offset="8">
          <el-button type="primary" @click.native.prevent="fileVisible = true">导入信息</el-button>
          <el-button type="success" @click.native.prevent="exportExcel()">导出信息</el-button>
        </el-col>
      </el-row>

      <el-dialog style="text-align: center;" title="文件上传" :visible.sync="fileVisible" width="37%" append-to-body>
        <el-form ref="file_ref">
          <el-upload class="upload-demo" drag action="action" multiple :before-upload="beforeUpload"
            :show-file-list="true" :auto-upload="false" :http-request="upload" ref="uploadBox">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip" style="text-align: center;">只能上传execl文件</div>
          </el-upload>
        </el-form>
        <el-button style="margin-left: 10px; margin-top: 10px;" size="small" type="success"
          @click="submitFile">上传文件</el-button>
      </el-dialog>



      <!--用户列表区域-->
      <el-table :data="userList.slice((pagenum - 1) * pagesize, pagenum * pagesize)" :border="true" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName"></el-table-column>
        <el-table-column label="用户角色" prop="roleName"></el-table-column>
        <el-table-column label="是否激活" prop="status">
          <template slot-scope="scope">
            <div v-if="scope.row.status == '1'">
              <el-tag type="success">已激活</el-tag>
            </div>
            <div v-else="scope.row.status == '0'">
              <el-tag type="info">未激活</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!--查看按钮-->
            <el-tooltip effect="dark" content="查看该用户详细信息" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-setting" size="mini"
                @click="getUserInformation(scope.row)"></el-button>
            </el-tooltip>
            <!--修改按钮-->
            <el-button type="warning" icon="el-icon-edit" size="mini"
              @click="updateUserInformation(scope.row)"></el-button>
            <!--删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click.native.prevent="deleteUser(scope.row.userId)"></el-button>
          </template>
        </el-table-column>
      </el-table>


      <!--用户详细信息-->
      <el-dialog title="用户详细信息" :visible.sync="detailedVisible" width="50%">
        <!--用户详细信息主体-->
        <el-form :model="userDetailForm" ref="userDetailFormRef" label-width="90px">
          <template>
            <el-radio-group v-model="size">
              <el-radio label="">默认</el-radio>
              <el-radio label="medium">中等</el-radio>
              <el-radio label="small">小型</el-radio>
              <el-radio label="mini">超小</el-radio>
            </el-radio-group>

            <el-descriptions class="margin-top" :column="3" :size="size" border>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user"></i>
                  用户名
                </template>
                {{ userDetailForm.username }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user-solid"></i>
                  用户昵称
                </template>
                {{ userDetailForm.nickName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-female"></i>
                  用户性别
                </template>
                {{ userDetailForm.sex == 1 ? "男" : "女" }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-collection-tag"></i>
                  年龄
                </template>
                {{ userDetailForm.age }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-phone-outline"></i>
                  电话号码
                </template>
                {{ userDetailForm.phone }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-tickets"></i>
                  用户角色
                </template>
                <el-tag size="small">{{ userDetailForm.roleName }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-date"></i>
                  出生日期
                </template>
                {{ userDetailForm.birthday }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-postcard"></i>
                  政治面貌
                </template>
                {{ userDetailForm.identity }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-school"></i>
                  教育程度
                </template>
                {{ userDetailForm.education }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-office-building"></i>
                  所在单位
                </template>
                {{ userDetailForm.unitName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-s-home"></i>
                  家庭住址
                </template>
                {{ userDetailForm.address }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-form>
      </el-dialog>

      <!--修改用户信息-->
      <el-dialog title="修改用户信息" :visible.sync="updateDetailedVisible" width="50%">
        <!--用户详细信息主体-->
        <el-form :model="updateUserDetailForm" :rules="addUserRules" ref="updateUserDetailFormRef" label-width="90px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="updateUserDetailForm.username"></el-input>
          </el-form-item>
          <el-form-item label="电话号码：" prop="phone">
            <el-input v-model="updateUserDetailForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="updateUserDetailForm.password"></el-input>
          </el-form-item>
          <!-- <el-form-item label="用户角色：" prop="roleName">
            <el-select v-model="updateUserDetailForm.roleName" placeholder="请选择">
              <el-option v-for="item in roleName" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="用户昵称：" prop="nickName">
            <el-input v-model="updateUserDetailForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="年龄：" prop="age">
            <el-input v-model="updateUserDetailForm.age"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="updateUserDetailForm.sex" placeholder="请选择">
              <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期：" prop="birthday">
            <el-date-picker v-model="updateUserDetailForm.birthday" value-format="yyyy-MM-dd" type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="家庭住址：" prop="address">
            <el-input v-model="updateUserDetailForm.address"></el-input>
          </el-form-item>
          <el-form-item label="所在单位：" prop="unitName">
            <el-input v-model="updateUserDetailForm.unitName"></el-input>
          </el-form-item>
          <el-form-item label="教育程度：" prop="education">
            <el-select v-model="updateUserDetailForm.education" placeholder="请选择">
              <el-option v-for="item in educationList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="政治面貌：" prop="identity">
            <el-select v-model="updateUserDetailForm.identity" placeholder="请选择">
              <el-option v-for="item in identityList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateDetailedVisible = false">取 消</el-button>
          <el-button type="primary" @click.native.prevent="updateUser(updateUserDetailForm)">修 改</el-button>
        </span>
      </el-dialog>

      <el-dialog title="添加用户" :visible.sync="addUserdialogVisible" width="50%" @close="addUserDialogClosed()">
        <!--添加用户信息对话框的主体-->
        <el-form :model="addUserForm" :rules="addUserRules" ref="addUserFormRef" label-width="90px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="电话号码：" prop="phone">
            <el-input v-model="addUserForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="用户角色：" prop="roleId">
            <el-select v-model="addUserForm.roleId" placeholder="请选择">
              <el-option v-for="item in roleName" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户昵称：" prop="nickName">
            <el-input v-model="addUserForm.nickName"></el-input>
          </el-form-item>
          <el-form-item label="年龄：" prop="age">
            <el-input v-model="addUserForm.age"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="addUserForm.sex" placeholder="请选择">
              <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期：" prop="birthday">
            <el-date-picker v-model="addUserForm.birthday" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="家庭住址：" prop="address">
            <el-input v-model="addUserForm.address"></el-input>
          </el-form-item>
          <el-form-item label="所在单位：" prop="unitName">
            <el-input v-model="addUserForm.unitName"></el-input>
          </el-form-item>
          <el-form-item label="教育程度：" prop="education">
            <el-select v-model="addUserForm.education" placeholder="请选择">
              <el-option v-for="item in educationList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="政治面貌：" prop="identity">
            <el-select v-model="addUserForm.identity" placeholder="请选择">
              <el-option v-for="item in identityList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.native.prevent="addUser(addUserForm)">确 定</el-button>
        </span>
      </el-dialog>

      <!--分页区域-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum"
        :page-sizes="[1, 2, 5, 10]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"
        style="margin-top: 5px; text-align: center;">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
const formData = new FormData()
import {
  GetUserInfoListAPI,
  GetUserInfoListByParamsAPI,
  RemoveUserInfoAPI,
  UpdateUserInfoAPI,
  AddUserInfoAPI,
  ImportInfo,
  ExportInfo
} from '@/components/utils/api/user_api.js'
export default {
  data() {
    let checkAge = (rule, value, callback) => {
      let reg = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/; //年龄是1-120之间有效
      if (value == undefined) {
        callback([new Error("帐号输入不合法")]);
      } else {
        if (value && value.length > 0) {
          if (!reg.test(value)) {
            callback([new Error("年龄输入不合法")]);
          } else {
            callback();
          }
        } else if (value.length == 0) {
          callback();
        } else {
          callback(new Error("年龄输入不合法"));
        }
      }
    }
    return {
      sexList: [
        {
          value: 0,
          label: "女"
        },
        {
          value: 1,
          label: "男"
        },
      ],
      roleName: [
        {
          value: "10001",
          label: "普通用户"
        },
        {
          value: "10002",
          label: "教师用户"
        },
        {
          value: "10000",
          label: "管理员用户"
        },
      ],
      identityList: [
        {
          value: "群众",
          label: "群众"
        }, {
          value: "共青团员",
          label: "共青团员"
        }, {
          value: "预备党员",
          label: "预备党员"
        }, {
          value: "正式党员",
          label: "正式党员"
        }
      ],
      educationList: [
        {
          value: "无",
          label: "无"
        }, {
          value: "专科",
          label: "专科"
        }, {
          value: "全日制本科",
          label: "全日制本科"
        }, {
          value: "非全日制本科",
          label: "非全日制本科"
        }, {
          value: "硕士",
          label: "硕士"
        }, {
          value: "博士",
          label: "博士"
        }, {
          value: "博士后",
          label: "博士后"
        }
      ],// 权限列表
      updateUserDetailForm: [],
      updateDetailedVisible: false,
      detailedVisible: false,// 用户详细信息弹窗可视化
      userDetailForm: [],
      selectBy: '',
      userList: [],
      timeDefaultShow: '',
      size: '',
      total: 0,
      pagesize: 10,
      pagenum: 1,
      // 增加用户数据
      addUserdialogVisible: false,
      addUserForm: {},
      addUserRules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        }],
        password: [{
          required: true, message: '请输入用户密码', trigger: 'blur'
        }],
        roleName: [{
          required: true, message: '请选择用户角色', trigger: 'blur'
        }],
        nickName: [{
          required: true, message: '请输入用户昵称', trigger: 'blur'
        }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: "请输入正确的手机号码"
          }
        ],
        age: [
          {
            required: true,
            message: "请输入合法的年龄",
            validator: checkAge,//从这里调用上面的方法即可
            trigger: "blur",
          },
        ],
        sex: [{
          required: true, message: '请选择用户性别'
        }],
        birthday: [{
          required: true, message: '请选择用户出生日期'
        }],
        education: [{
          required: true, message: '请选择用户政治面貌'
        }],
        identity: [{
          required: true, message: '请选择用户教育程度'
        }],
        roleId: [{
          required: true, message: '请选择用户角色'
        }],
      },
      // 修改用户密码数据
      // updateUserpassworddialogVisible: false,
      // updateUserpasswordForm: { username: '', password: '' },
      // updateUserpasswordFormRules: {},
      // 修改用户权限数据
      updateUserRoledialogVisible: false,
      updateUserRoleForm: { username: '', id: '' },
      updateUserRoleFormRules: {},
      userDetailFormRules: {},
      fileVisible: false,
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
     // 导出excel表
     exportExcel(){
      window.open('http://lintingfeng.top:9527/excel/exportUserInfoExcel',"_blank")
    },

    //上传文件前
    beforeUpload(file) {
      if (file) {
        formData.append('file', file)
        console.log("🚀 ~ file: Home.vue:251 ~ beforeUpload ~ formData:", formData)
      }
      else {
        this.$message.error("上传文件时出错")
      }
    },
    submitFile() {
      this.$refs.uploadBox.submit()
      // this.fileVisible = false
    },

    //上传
    upload() {
      ImportInfo(formData).then(res => {
        console.log("file: UserManage.vue:474  res", res)
        // if (res.data.code == 200) {
        //   res.data.data.forEach(element => {
        //     this.annexId = element.id
        //   });
        //   this.$message.success("上传文件成功")
        // } else {
        //   this.$message.error("上传文件失败")
        // }
      })
    },
    // 修改时获取当行用户详细信息
    updateUserInformation(info) {
      this.updateDetailedVisible = true
      this.updateUserDetailForm = info
    },
    // 获取当行用户详细信息
    getUserInformation(information) {
      this.userDetailForm = information
      this.detailedVisible = true
    },

    // 获取用户列表
    getUserList() {
      GetUserInfoListAPI({}).then(res => {
        // console.log(res.data)
        this.userList = res.data.data
        this.total = this.userList.length
      })
    },

    // 查询用户信息按钮
    async selectById(userId) {
      GetUserInfoListByParamsAPI({
        username: userId
      }).then(res => {
        console.log("res", res)
        this.userList = res.data.data
        this.total = this.userList.length
      })

    },

    // 删除按钮事件
    async deleteUser(id) {
      const deleteres = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteres !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      var params = {
        id: id
      }
      RemoveUserInfoAPI(params).then(res => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg)
          this.getUserList()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    // 重置添加用户信息对话框
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    // // 重置修改用户密码对话框
    // updateUserpassworddialog() {
    //   this.$refs.updateUserpasswordFormRef.resetFields()
    // },
    // 重置修改用户权限对话框
    updateUserRoledialog() {
      this.$refs.updateUserRoleFormRef.resetFields()
    },

    // 添加用户
    async addUser(form) {
      AddUserInfoAPI(form).then(res => {
        if (res.data.code == 200) {
          console.log(res.data.data);
          this.addUserdialogVisible = false
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
        this.getUserList()
      })
      // const params = new URLSearchParams
      // params.append('username', id)
      // this.addUserdialogVisible = false
      // const res = await this.$http.post('/user/insert', params)
      // if (res == null) return this.$message.error('添加用户失败')
      // if (res.data.code != 20000) return this.$message.error(res.data.msg)
      // this.$message.success(res.data.msg)
    },

    // 修改用户信息
    async updateUser(form) {
      form.id = form.userId;
      UpdateUserInfoAPI(form).then(res => {
        if (res.data.code == 200) {
          this.updateDetailedVisible = false
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
        this.getUserList()
      })
      // const params = new URLSearchParams
      // params.append('username', this.updateUserpasswordForm.username)
      // params.append('password', this.updateUserpasswordForm.password)
      // const updateUserres = await this.$http.post('/user/updatePassword', params)
      // if (updateUserres.data.code != 20000) return this.$message.error('修改用户密码失败')
      // this.$message.success(updateUserres.data.msg)
      // this.updateUserpassworddialogVisible = false
    },

    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.pagesize = newSize
    },

    //监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.pagenum = newPage
    },

  }
}
</script>